package plugin;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;



public class UPCComPlugin implements IProductIDPlugin {
	private final int ONE_SECOND = 1000;
	
	@Override
	public String identifyProduct(String barcode) throws Exception {
		// Build request
		String xmlrpcRequest = "<?xml version=\"1.0\"?><methodCall><methodName>lookup</method" +
				"Name><params><param><value><struct><member><name>rpc_key</name><value><strin" +
				"g>e790f762b14f58e8e801c9067dfad36f890cfb06</string></value></member><member>" +
				"<name>upc</name><value><int>" + barcode + "</int></value></member></struct><" +
				"/value></param></params></methodCall>";
		
		// Open the connection
		URL url = new URL( "http://www.upcdatabase.com/xmlrpc");
		URLConnection conn = url.openConnection();
		
		// Set some parameters
		((HttpURLConnection)conn).setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setConnectTimeout(ONE_SECOND);
		conn.setReadTimeout(ONE_SECOND * 5); 
		
		// Send the request
		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		wr.write(xmlrpcRequest);
		wr.flush();
		
		// Retrieve the response
		String result = null;
		BufferedReader rd = new BufferedReader( new InputStreamReader(conn.getInputStream()));
		String line =null;
		while ((line = rd.readLine()) != null){
			if (line.startsWith("<member><name>description</name><value><string>")){
				result = line;
			}
		}
		wr.close();
		rd.close();
		
		if (result != null){
			String[] parts = result.split("[<>]");
			return parts[10];
		}
		throw new Exception("Couldn't resolve barcode");

	}

}
